package com.rockcent.api.controller;

import com.rockcent.api.Routes;
import com.rockcent.common.common.JsonResult;
import com.rockcent.common.common.PageResult;
import com.rockcent.common.common.RestDoing;
import com.rockcent.common.controller.BaseController;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.helper.MallMemberHelper;
import com.rockcent.helper.SysMessageHelper;
import com.rockcent.mall.lib.constants.SysMessageConstants;
import com.rockcent.mall.lib.domain.MallMember;
import com.rockcent.mall.lib.domain.MallMemberRechargeFlow;
import com.rockcent.mall.lib.domain.enumclass.AuditStatus;
import com.rockcent.mall.lib.domain.enumclass.MallMemberFundTransactionType;
import com.rockcent.mall.lib.domain.enumclass.MallMemberRechargeType;
import com.rockcent.mall.lib.domain.enumclass.MallMemberStatus;
import com.rockcent.mall.lib.dto.MallMemberRechargeFlowDto;
import com.rockcent.mall.lib.repository.MallMemberRechargeFlowRepository;
import com.rockcent.mall.lib.repository.MallMemberRepository;
import com.rockcent.service.MallMemberRechargeSrv;
import com.rockcent.service.MallMemberSrv;
import org.apache.commons.lang3.EnumUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.text.MessageFormat;
import java.util.Date;

/**
 * Created by zhangjh on 2017/3/8.
 * 平台充值管理
 */
@RestController
@RequestMapping(value = Routes.API_VERSION)
public class MallMemberRechargeAuditController  extends BaseController {

    private final Logger log = LoggerFactory.getLogger(MallMemberRechargeAuditController.class);

    @Autowired
    private MallMemberSrv mallMemberSrv;

    @Autowired
    private MallMemberRechargeSrv mallMemberRechargeSrv;

    @Autowired
    private MallMemberRechargeFlowRepository mallMemberRechargeFlowRepository;

    @Autowired
    private MallMemberRepository mallMemberRepository;

    /**
     * @api {put} /v1/mall/member/recharge/audit R 平台充值审核
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {long} id <code>必选参数</code> ID
     * @apiParam {String} auditStatus <code>必选参数</code> 状态 ：PASS("审核通过"),REFUSE("审核不通过")
     * @apiParam {String} remark <code>可选参数</code> 审核意见:审核不通过,审核意见不能为空
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功"
     * }
     */
    @Transactional
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_AUDIT, method = RequestMethod.PUT)
    public JsonResult mallMemberRechargeAudit(@RequestBody MallMemberRechargeFlowDto dto, HttpServletRequest request) {
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallMemberRechargeFlow.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MallMemberRechargeFlow mallMemberRechargeFlow = mallMemberRechargeFlowRepository.findByIdAndAuditStatus(dto.getId(), AuditStatus.WAIT);
            if (mallMemberRechargeFlow == null) {
                jsonResult.remind(MallMemberRechargeFlow.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            if (mallMemberRechargeFlow.getAuditStatus() != AuditStatus.WAIT) {
                jsonResult.remind("此充值已审核",log);
                return;
            }
            if (StringUtils.isBlank(dto.getAuditStatus()) || !EnumUtils.isValidEnum(AuditStatus.class, dto.getAuditStatus())) {
                jsonResult.remind("审核状态只允许 PASS(\"审核通过\"),REFUSE(\"审核不通过\")",log);
                return;
            }
            SysMessageConstants sysMessageConstants = null;
            String content = null;
            MallMember mallMember = mallMemberRepository.findById(mallMemberRechargeFlow.getMallMemberId());
            if (AuditStatus.REFUSE == AuditStatus.valueOf(dto.getAuditStatus())) {
                String remark = dto.getRemark();
                if (StringUtils.isBlank(remark)) {
                    jsonResult.remind("审核不通过的情况下, 审核意见不能为空",log);
                    return;
                }
                mallMemberRechargeFlow.setRemark(remark);


                //是否是首次充值
                if (MallMemberStatus.AUDITING == mallMember.getStatus() || MallMemberStatus.AUDIT_REFUSE == mallMember.getStatus()) {
                    mallMember.setStatus(MallMemberStatus.AUDIT_REFUSE);
                }

                mallMemberRepository.save(mallMember);

                if (mallMember.getStatus() == MallMemberStatus.MEMBER) {//成为会员后的后续充值
                    String constantContent = SysMessageConstants.M2M_MALL_MEMBER_RECHARGE_AUDIT_UNPASSS.getContent();
                    content = MessageFormat.format(constantContent, DateUtils.formatDate(mallMemberRechargeFlow.getDateCreated()), mallMemberRechargeFlow.getRechargeAmount(), remark);
                    sysMessageConstants = SysMessageConstants.M2M_MALL_MEMBER_RECHARGE_AUDIT_UNPASSS;
                } else {//开通会员
                    String constantContent = SysMessageConstants.M2M_NOT_MALL_MEMBER_RECHARGE_AUDIT_UNPASSS.getContent();
                    content = MessageFormat.format(constantContent, remark);
                    sysMessageConstants = SysMessageConstants.M2M_NOT_MALL_MEMBER_RECHARGE_AUDIT_UNPASSS;
                }


            }
            if (AuditStatus.PASS == AuditStatus.valueOf(dto.getAuditStatus())) {
                //保存资金流水
                mallMemberSrv.changeMallMemberFund(mallMemberRechargeFlow.getRechargeAmount(), mallMemberRechargeFlow.getMallMemberId(), MallMemberFundTransactionType.OUTLINE_RECHARGE, mallMemberRechargeFlow.getSeqNo());
                mallMemberRechargeFlow.setRemark("通过");
                if (mallMember.getStatus() == MallMemberStatus.MEMBER) {
                    sysMessageConstants=SysMessageConstants.M2M_NOT_MALL_MEMBER_RECHARGE_AUDIT_PASSS;
                }
            }
            mallMemberRechargeFlow.setAuditStatus(AuditStatus.valueOf(dto.getAuditStatus()));
            mallMemberRechargeFlow.setDateAudited(new Date());
            mallMemberRechargeFlowRepository.save(mallMemberRechargeFlow);

            //广播消息
            SysMessageHelper.SINGLETON.pushSysMsg(sysMessageConstants, content, mallMemberRechargeFlow.getMallId(),null);

        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/member/recharge/audit_page R 平台充值审核分页
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {String} auditStatus <code>必选参数</code> 状态 ：WAIT("待审核"),AUDITED("已审核或者全部状态"), PASS("审核通过"),REFUSE("审核不通过")
     * @apiParam {String} mallName <code>可选参数</code> 平台名称
     * @apiParam {String} mallId <code>可选参数</code> 平台商ID
     * @apiParam {String} rechargeAccount <code>可选参数</code> 汇款帐号
     * @apiParam {String} beginDate <code>可选参数</code> 提交开始时间
     * @apiParam {String} endDate <code>可选参数</code> 提交结束时间
     * @apiParam {String} rechargeDate <code>可选参数</code> 汇款时间
     * @apiParam {dec} rechargeAmount <code>可选参数</code> 汇款金额
     *
     * @apiSuccess  {String} rechargeVoucher  汇款凭证
     * @apiSuccess {date} dateAudited  审核时间
     * @apiSuccess {String} mallId  平台商ID
     * @apiSuccess {String} mallName  平台名称
     * @apiSuccess {date} rechargeDate  汇款时间
     * @apiSuccess {BigDecimal} rechargeAmount  汇款金额
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *      {
     *        "id": 10,
     *        "dateCreated": "2016-06-13 18:28:41",
     *        "dateAudited": "2016-06-13 18:28:41",
     *        "mallId": 12,
     *        "mallName": "平台名称",
     *        "rechargeAccount": "3423453246345254",
     *        "rechargeDate": "2016-06-13",
     *        "rechargeAmount": "23.23",
     *        "rechargeVoucher": "http://34345243.jpg"
     *      },
     *      ........　
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_AUDIT_PAGE, method = RequestMethod.GET)
    public JsonResult mallMemberRechargeAuditPage(MallMemberRechargeFlowDto dto, HttpServletRequest request) {
        RestDoing doing = jsonResult -> {
            if(StringUtils.isBlank(dto.getAuditStatus()) || !EnumUtils.isValidEnum(AuditStatus.class,dto.getAuditStatus())){
                jsonResult.errorParam("审核状态为空", log);
                return;
            }
            PageResult<MallMemberRechargeFlowDto> pageResult = mallMemberRechargeSrv.findMallMemberRechargePage(dto, getPage(dto.getPageNo(), dto.getPageSize()));
            pageResult.setUrl(Routes.MALL_MEMBER_RECHARGE_AUDIT_PAGE);
            jsonResult.data = pageResult;
        };
        return doing.go(request, log);
    }

    /**
     * @api {get} /v1/mall/member/recharge/voucher R 平台充值审核详情
     * @apiGroup mall_member
     * @apiVersion 1.0.0
     * @apiHeader {String} userToken 用户token
     * @apiHeader {String} domain    请求域名
     * @apiParam {long} id <code>必选参数</code> ID
     * @apiParam {String} rechargeVoucher <code>可选参数</code> 汇款凭证
     * @apiSuccessExample {json} Success-Response:
     * {
     *   "code": "1",
     *   "desc": "成功",
     *   "data": [
     *      {
     *        "id": 10,
     *        "rechargeVoucher": "http://34345243.jpg"
     *      }
     *   ]
     * }
     */
    @RequestMapping(value = Routes.MALL_MEMBER_RECHARGE_VOUCHER, method = RequestMethod.GET)
    public JsonResult checkMallMemberRechargeVoucher(MallMemberRechargeFlowDto dto, HttpServletRequest request){
        RestDoing doing = jsonResult -> {
            if (dto.getId() == null) {
                jsonResult.remind(MallMemberRechargeFlow.CHECK_ID_IS_NOT_NULL,log);;
                return;
            }
            MallMemberRechargeFlow mallMemberRechargeFlow = mallMemberRechargeFlowRepository.findOne(dto.getId());
            if (mallMemberRechargeFlow == null) {
                jsonResult.remind(MallMemberRechargeFlow.REMIND_RECORD_IS_NOT_EXIST,log);;
                return;
            }
            jsonResult.data = mallMemberRechargeFlow;
        };
        return doing.go(request, log);
    }
}
